﻿/*************************************************
  Copyright (C), 2014-2017, lmd Tech. Co., Ltd.
  文 件  名:	
  作       者:	陈佳
  版       本:	1.0        
  完成日期:	2017//      
  功能描述:	
  主要功能: 
*************************************************/
using System;
using UnityEngine;

namespace CxExtension
{
	/// <summary>
	/// 封装的计时器,当时间积累足够时,自动调用TriggerFunc
	/// </summary>
	public class CTimer:ITimer
	{
		private float mUsedtime;                       //使用时间
		private float mInterval;                           //间隔时间
		private TState mState = TState.Idle;                      //
		public event Action onComplete;//	

		public TState State { get { return mState; } }

		public float Interval { get { return mInterval; } }

		public void SetInterval(float v)
		{
			mInterval = v;
		}



		public void SetState(TState v)
		{
			mState = v;
		}


		public CTimer(float duration)
		{
			mUsedtime = 0;
			if (duration <= 0)
			{
				duration = 0.02f;
				Debug.LogErrorFormat("持续时间不能小于等于0");
			}
			mInterval = duration;
		}
		public virtual void Reset()
		{
			mUsedtime = 0;
			SetState(TState.Runing);
		}

		protected void ComleteInternal()
		{
			if (onComplete != null) onComplete();
		}

		// Update is called once per frame
		public virtual bool Update(float dt)
		{
			if (mState == TState.Pause || mState == TState.Idle)
			{
				return false;
			}
			if (mState == TState.Stop)
			{
				return true;
			}
			
			mUsedtime += dt;
			var r = false;
			while(mUsedtime >= mInterval)
			{
				mUsedtime -= mInterval;
				SetState(TState.Complete);
				r = true;
			}
			return r;
		}

		public virtual void Stop()
		{
			SetState(TState.Stop);
		}
	}
}
